﻿using System;
using System.Collections.Generic;
using System.Data.Entity; // needed for lambda includes
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;



namespace TheCup.ApiControllers
{
    public class CourseController : ApiController
    {
        TheCupContext ctx = new TheCupContext();

        public IEnumerable<Course> Get()
        {
            return (from course in ctx.Courses
                    orderby course.Name
                    select course).AsEnumerable();
        }

        public IEnumerable<Course> Get(string startsWith)
        {
            return (from course in ctx.Courses
                    where course.Name.StartsWith(startsWith)
                    select course).OrderBy(c => c.Name).AsEnumerable();
        }
        
        public Course Get(int id)
        {
            return (from course in ctx.Courses.Include(t => t.Tees)
                    where course.Id.Equals(id)
                    select course).FirstOrDefault();
        }

        [Authorize]
        public void Post([FromBody]Course e)
        {
            if (ModelState.IsValid)
            {
                e.CountryCodeISO3166Alpha2 = e.CountryCodeISO3166Alpha2.Trim().ToUpper();
                ctx.Courses.Add(e);
                ctx.SaveChanges();
            }
        }

        [Authorize]
        public void Put(int id, [FromBody]Course c)
        {
            if (ModelState.IsValid)
            {
                Course course = this.Get(id);
                course = c;
                ctx.SaveChanges();
            }
        }

        [Authorize]
        public void Delete(int id)
        {
            Course course = this.Get(id);
            if (course != null)
            {
                ctx.Courses.Remove(course);
                ctx.SaveChanges();
            }
        }
    }

}